package com.baizhi.service.impl;

import com.baizhi.entity.Comment;
import com.baizhi.dao.CommentMapper;
import com.baizhi.entity.User;
import com.baizhi.service.FeignUserService;
import com.baizhi.service.ICommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangsan
 * @since 2022-06-28
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Autowired
    private FeignUserService fus;
    @Override
    public IPage<Comment> selectCommentByPage(int pageNo, int pageSize, int schoolId) {
        IPage<Comment> page=new Page(pageNo,pageSize);
        QueryWrapper<Comment> wrapper=new QueryWrapper<>();
        wrapper.eq("school_id",schoolId).isNull("parent_id").orderByDesc("comment_time");
        page = baseMapper.selectPage(page, wrapper);
        //page里面只有一级评论，我们需要给一级评论对应的二级评论赋值
        List<Comment> records = page.getRecords();
        for(Comment comment:records){
            Integer id = comment.getId();//父评论的id值
            QueryWrapper<Comment> wrapper2=new QueryWrapper<>();
            wrapper2.eq("parent_id",id).orderByDesc("comment_time");
            IPage<Comment> childPage=new Page<>(1,3);
            List<Comment> comments = baseMapper.selectPage(childPage, wrapper2).getRecords();
            //把二级评论中的user对象查询出来赋值
            for(Comment c:comments){
                //把comment里面的学生对象查询出来
                Integer userId = c.getUserId();
                User user = fus.selectOne(userId);
                c.setUser(user);
            }
            comment.setChildrenComment(comments);

            //把comment里面的学生对象查询出来
            Integer userId = comment.getUserId();
            User user = fus.selectOne(userId);
            comment.setUser(user);
        }
        return page;
    }
    @Autowired
    //获取RedisTemplate工具
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public void giveLikes(int commentId) {
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        vo.increment("comment:"+commentId+":likes");
    }
}
